<?php
class BaeDataSource{
	private $connection = null;
	
	public function __construct(){
		/*替换为你自己的数据库名（可从管理中心查看到）*/
		$dbname = 'BBtLIaOEkeaVElxrAwvw';
		 
		/*从环境变量里取出数据库连接需要的参数*/
		$host = getenv('HTTP_BAE_ENV_ADDR_SQL_IP');
		$port = getenv('HTTP_BAE_ENV_ADDR_SQL_PORT');
		$user = getenv('HTTP_BAE_ENV_AK');
		$pwd = getenv('HTTP_BAE_ENV_SK');

		$this->connection = @mysql_connect("{$host}:{$port}",$user,$pwd,true);
		if(!$this->connection) {
			die("Connect Server Failed: " . mysql_error());
		}
		/*连接成功后立即调用mysql_select_db()选中需要连接的数据库*/
		if(!mysql_select_db($dbname, $this->connection)) {
			die("Select Database Failed: " . mysql_error($this->connection));
		}
		
		$this->execute("SET character_set_results = 'utf8', character_set_client = 'binary', character_set_connection = 'utf8'");
	}

	public function setDebug($status=true){
		if($status)
		{
			$this->connection->debug = true;
		}
		else
		{
			$this->connection->debug = false;
		}
	}

	public function getConnection(){
		return $this->connection;
	}

	public function selectLimit($sql, $rows=10, $offset=0, $args=false){
		try
		{
			$sql = $this->prepareSql($sql, $args);
			$sql .= " limit $offset, $rows";
			
			$resultSet = mysql_query($sql, $this->connection);
				
			if($resultSet && mysql_num_rows($resultSet) > 0)
			{
				$result = array();
				while ($row = mysql_fetch_assoc($resultSet)) {
			        $result = $row;
			    }
			    
			    return $result;
			}
				
		}
		catch(exceptions $e)
		{
			$this->logErrorMsg($e);
		}
		
		return false;
	}

	public function getAll($sql, $args = array()){
		try
		{
			$resultSet = mysql_query($this->prepareSql($sql, $args), $this->connection);
				
			if($resultSet && mysql_num_rows($resultSet) > 0)
			{
				$result = array();
				while ($row = mysql_fetch_assoc($resultSet)) {
			        $result = $row;
			    }
			    
			    return $result;
			}
				
		}
		catch(exceptions $e)
		{
			$this->logErrorMsg($e);
		}
		
		return false;
	}

	public function getOne($sql, $args = array()){
		try
		{
			$resultSet = mysql_query($this->prepareSql($sql, $args), $this->connection);
				
			if($resultSet && mysql_num_rows($resultSet) > 0)
			{
				$row =  mysql_fetch_row($resultSet);
				return $row[0];
			}
				
		}
		catch(exceptions $e)
		{
			$this->logErrorMsg($e);
		}
		
		return false;
	}

	public function getRow($sql, $args = array())
	{
		try
		{
			$resultSet = mysql_query($this->prepareSql($sql, $args), $this->connection);
				
			if($resultSet && mysql_num_rows($resultSet) > 0)
			{
				return mysql_fetch_assoc($resultSet);
			}
				
		}
		catch(exceptions $e)
		{
			$this->logErrorMsg($e);
		}
		
		return false;
	}

	public function execute($sql, $args = array()){
		try
		{
			mysql_query($this->prepareSql($sql, $args), $this->connection);
			
			return mysql_affected_rows($this->connection);
		}
		catch(exceptions $e)
		{
			$this->logErrorMsg($e);
		}

		return false;
	}

	public function insert($sql, $args = array()){
		try
		{
			$resultSet = mysql_query($this->prepareSql($sql, $args), $this->connection);
				
			if($resultSet)
			{
				$insertId = mysql_insert_id($this->connection);
				return $insertId;
			}
				
		}
		catch(exceptions $e)
		{
			$this->logErrorMsg($e);
		}
		
		return false;
	}

	public function update($sql, $args = array()){
		try
		{
			return $this->execute($sql, $args);
		}
		catch(exceptions $e)
		{
			$this->logErrorMsg($e);
		}
		return false;
	}

	private function logErrorMsg($e = null){
		ob_start('db_error');
		
		echo "DB Error, could not query the database\n";
		
		if($e != null)
		{
			var_export($e);
		}
		
		echo $this->connection->ErrorMsg();
		
		$logInfo = ob_get_clean();
		
		sql_log($logInfo);
	}

	private function prepareSql($sql, $args)
	{
		if (check_array($args))
		{
			if (str_word_count($sql, '?') != count($args))
			{
				return false;
			}
		}
			
		$ph = array('?');
			
		foreach ($args as &$v)
		{
			$v = mysql_escape_string($v);
		}
			
		str_replace($ph, $args, $sql);

		return $sql;
	}
}